package utility;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;

public class NameMemmory {
	
	private String name;
	
	static NameMemmory nameMemory;
	
	private NameMemmory(){}
	
	static public NameMemmory getInstace(){
		if(nameMemory==null){
			nameMemory=new NameMemmory();
		}
		return nameMemory;
	}
	
	public String getName(){
		return getNameFromFile();
	}
	
	private String getNameFromFile(){
		String s="Giocatore";
		File file = new File("name.txt");
		boolean empty = !file.exists() || file.length() == 0;
		if(!empty){
			FileReader f;
			try {
				f=new FileReader("name.txt");
				BufferedReader b;
				b=new BufferedReader(f);
				s=b.readLine();
				return s;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return s;


		}else{
			return s;
		}
	}

	public void setNameInFile(String name){
		String s="giocatore";
		File file = new File("name.txt");
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		FileOutputStream prova;
		try {
			prova = new FileOutputStream("name.txt");
			PrintStream scrivi = new PrintStream(prova);
			scrivi.println(name);
			scrivi.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
